/*
 * FileComparisor.cpp
 *
 *  Created on: Aug 20, 2013
 *      Author: jeff
 */
#include <stdlib.h>
#include <sstream>
#include <hash/md5.h>
#include "StreamComparisor.h"

namespace fs {

Json::Value StreamComparisor::compare()
{
	MD5 md5;
	MD5 block_md5;

	char* buffer_left = new char[buffer_size];
	char* buffer_right = new char[buffer_size];

	int left_buffer_length= read_left(buffer_left, buffer_size);
	int right_buffer_length = read_right(buffer_right, buffer_size);

	md5.Init();
	while((0 != left_buffer_length) || (0 != right_buffer_length))
	{
		md5.Update((unsigned char*)buffer_left, left_buffer_length);
		/*if(0 < left_buffer_length)
		{
			block_md5.Init();
			block_md5.Update((unsigned char*)buffer_left, left_buffer_length);
			block_md5.Final();
			md5.Update((unsigned char *)block_md5.digestChars, 33);
		}
		block[JSON_KEY_HASH] = block_md5.digestChars;*/

		//Json::Value block;
		diff(buffer_left, left_buffer_length, buffer_right, right_buffer_length, /*&block*/&root);
		//(*root)[JSON_KEY_BLOCK].append(block);

		left_buffer_length = read_left(buffer_left, buffer_size);
		right_buffer_length = read_right(buffer_right, buffer_size);
	}

	std::string right_file;
	delete[] buffer_left;
	delete[] buffer_right;

	md5.Final();
	root[JSON_KEY_HASH] = md5.digestChars;

	return root;
}

void StreamComparisor::setLeft(std::istream *left)
{
	stream_left = left;
	//cursor_left = stream_left->rdbuf();
	//cursor_left->pubseekpos (0, std::ios::in);
}

void StreamComparisor::setRight(std::istream *right)
{
	stream_right = right;
	//cursor_right = stream_right->rdbuf();
	//cursor_right->pubseekpos (0, std::ios::in);
}

void StreamComparisor::setOutput(std::ostream *output)
{
	stream_output = output;
}

int StreamComparisor::read_left(char * buffer, int length){
	return stream_left->readsome(buffer, length);
	//return cursor_left->sgetn(buffer, length);
}

int StreamComparisor::read_right(char * buffer, int length){
	return stream_right->readsome(buffer, length);
	//return cursor_right->sgetn(buffer, length);
}

void StreamComparisor::output_diff_data(int insert_length, const char * diff, Json::Value* segment)
{
	if(insert_length > 0)
	{
		stream_output->write(diff, insert_length);
	}
}

}
